package com.eksframework.commons.core.validator.annotations;

import com.eksframework.commons.core.base.EksDate;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

/**
 * 日期格式验证器
 *
 * @author chenfenghai
 */
public class DateFormatValidator implements ConstraintValidator<DateFormat, String> {

    private DateFormat dateFormat;

    /**
     * Initializes the validator in preparation for
     * {@link #isValid(String, ConstraintValidatorContext)} calls.
     * The constraint annotation for a given constraint declaration
     * is passed.
     * <p>
     * This method is guaranteed to be called before any use of this instance for
     * validation.
     * <p>
     * The default implementation is a no-op.
     *
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */
    @Override
    public void initialize(DateFormat constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        this.dateFormat = constraintAnnotation;
    }

    /**
     * Implements the validation logic.
     * The state of {@code value} must not be altered.
     * <p>
     * This method can be accessed concurrently, thread-safety must be ensured
     * by the implementation.
     *
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     * @return {@code false} if {@code value} does not pass the constraint
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 可以为null，如果不能为空，请使用非空注解
        if(Objects.isNull(value)){
            return true;
        }
        return EksDate.isDateTimeFormat(value, dateFormat.pattern());
    }
}
